home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / program / swagg_m.zip / MATH.SWG / 0009_PARSMATH.PAS.pas < prev    next >
Pascal/Delphi Source File  |  1993-05-28  |  2KB  |  70 lines

  1. │I'm writing a Program that draws equations.  It's fairly easy if you put
  2. │the equation in a pascal Variable like Y := (X+10) * 2, but I would like
  3. │the user to enter the equation, but I don't see any possible way to do
  4. │it.
  5.  
  6.  
  7.       ...One way of doing it is by using an "expression trees". Suppose
  8. you have the equation Y := 20 ÷ 2 + 3. In this equation, you can represent
  9. the expression 20 ÷ 2 + 3 by using "full" binary trees as such:
  10.  
  11.  
  12. figure 1                 a  ┌─┐
  13.                             │+│    <----- root of your expression
  14.                             └─┘
  15.                     b     /     \
  16.                       ┌─┐        ┌─┐ e
  17.                       │÷│        │3│
  18.                       └─┘        └─┘
  19.                       /  \
  20.                 c ┌──┐    ┌─┐ d
  21.                   │20│    │2│
  22.                   └──┘    └─┘
  23.  
  24.  
  25. (Note: a  "leaf" is a node With no left or right children - ie: a value )
  26.  
  27. ...The above expression are called infix arithmetic expressions; the
  28. operators are written in between the things on which they operate.
  29.  
  30. In our example, the nodes are visited in the order c, d, b, e, a,  and
  31. their Labels in this order are 20, 2, ÷, 3, +.
  32.  
  33.  
  34. Function Evaluate(p: node): Integer;
  35. { return value of the expression represented by the tree With root p }
  36. { p - points to the root of the expression tree                      }
  37. Var
  38.   T1, T2: Integer;
  39.   op: Char;
  40. begin
  41.   if (p^.left = nil) and (p^.right = nil) then    { node is a "leaf" }
  42.     Evaluate := (p^.Value)                        { simple Case      }
  43.   else
  44.     begin
  45.       T1 := Evaluate(p^.Left);
  46.       T2 := Evaluate(p^.Right);
  47.       op := p^.Label;
  48.       { apply operation }
  49.       Case op of
  50.         '+': Evaluate := (T1 + T2);
  51.         '-': Evaluate := (T1 - T2);
  52.         '÷': Evaluate := (T1 div T2);
  53.         '*': Evaluate := (T1 * T2);
  54.       end;
  55.     end
  56. end;
  57.  
  58.  
  59. ...Thus, using figure 1, we have:
  60.  
  61.               ┌──           ┌──
  62.               │             │ Evaluate(c) = 20
  63.               │ Evaluate(b) │ Evaluate(d) = 2
  64.               │             │ ApplyOp('÷',20,2) = 10
  65.    Evaluate(a)│             └──
  66.               │ Evaluate(e) = 3
  67.               │
  68.               │ ApplyOp('+',10,3) = 13
  69.               └─
  70.